{#     Copyright 2020, Kay Hayen, mailto:kay.hayen@gmail.com                    #}
{#                                                                              #}
{#     Part of "Nuitka", an optimizing Python compiler that is compatible and   #}
{#     integrates with CPython, but also works on its own.                      #}
{#                                                                              #}
{#     Licensed under the Apache License, Version 2.0 (the "License");          #}
{#     you may not use this file except in compliance with the License.         #}
{#     You may obtain a copy of the License at                                  #}
{#                                                                              #}
{#        http://www.apache.org/licenses/LICENSE-2.0                            #}
{#                                                                              #}
{#     Unless required by applicable law or agreed to in writing, software      #}
{#     distributed under the License is distributed on an "AS IS" BASIS,        #}
{#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #}
{#     See the License for the specific language governing permissions and      #}
{#     limitations under the License.                                           #}
{#                                                                              #}
static inline {{target.getTypeDecl()}} SLOT_{{nb_slot}}_{{target.getHelperCodeName()}}_{{left.getHelperCodeName()}}_{{right.getHelperCodeName()}}({{left.getVariableDecl("operand1")}}, {{right.getVariableDecl("operand2")}}) {
    {{left.getCheckValueCode("operand1")}}
    {{right.getCheckValueCode("operand2")}}

    {# This is supposed to be Python2 code #}
    const long a = {{left.getAsLongValueExpression("operand1")}};
    const long b = {{right.getAsLongValueExpression("operand2")}};

{% if operand in "+-" %}
    const long x = (long)((unsigned long)a {{operand}} b);
    bool no_overflow = ((x^a) >= 0 || (x^{{"~" if operand == "-" else ""}}b) >= 0);
{% if target.type_name in ("nuitka_bool", "nbool") %}
    bool t = !no_overflow || x != 0;

    {{target.getTypeDecl()}} result = {{target.getToValueFromBoolExpression("t")}};
    {{target.getTakeReferenceStatement("result")}}
    return result;
{% else %}
    if (likely(no_overflow)) {
        {{ target.getReturnFromLongExpressionCode("x") }}
    }
{% endif %}
{% elif operand == "*" %}
    const long longprod = (long)((unsigned long)a * b);
    const double doubleprod = (double)a * (double)b;
    const double doubled_longprod = (double)longprod;

    if (likely(doubled_longprod == doubleprod)) {
        {{ target.getReturnFromLongExpressionCode("longprod") }}
    } else {
        const double diff = doubled_longprod - doubleprod;
        const double absdiff = diff >= 0.0 ? diff : -diff;
        const double absprod = doubleprod >= 0.0 ? doubleprod : -doubleprod;

        if (likely(32.0 * absdiff <= absprod)) {
            {{ target.getReturnFromLongExpressionCode("longprod") }}
        }
    }
{% elif operand == "//" or nb_slot == "nb_divide" %}
    if (unlikely(b == 0)) {
        SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "integer division or modulo by zero");
        return {{target.getExceptionResultIndicatorValue()}};
    }

    /* TODO: Isn't this a very specific value only, of which we could
     * hardcode the constant result. Not sure how well the C compiler
     * optimizes UNARY_NEG_WOULD_OVERFLOW to this, but dividing by
     * -1 has to be rare anyway.
     */

    if (likely(b != -1 || !UNARY_NEG_WOULD_OVERFLOW(a))) {
        long a_div_b = a / b;
        long a_mod_b = (long)(a - (unsigned long)a_div_b * b);

        if (a_mod_b && (b ^ a_mod_b) < 0) {
            a_mod_b += b;
            a_div_b -= 1;
        }

        {{ target.getReturnFromLongExpressionCode("a_div_b") }}
    }
{% elif operand=="/" and "true_div" in nb_slot %}
    if (unlikely(b == 0)) {
        SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "division by zero");
        return {{target.getExceptionResultIndicatorValue()}};
    }

    if (a == 0) {
        if (b < 0) {
            {{ target.getReturnFromFloatConstantCode(-0.0) }}
        } else {
            {{ target.getReturnFromFloatConstantCode(0.0) }}
        }
    }

/* May need to resort to LONG code, which we currently do not
 * specialize yet. TODO: Once we do that, call it here instead.
 */
#if DBL_MANT_DIG < WIDTH_OF_ULONG
    if ((a >= 0 ? 0UL + a : 0UL - a) >> DBL_MANT_DIG || (b >= 0 ? 0UL + b : 0UL - b) >> DBL_MANT_DIG) {
    } else
#endif
    {
        double result = (double)a / (double)b;
        {{ target.getReturnFromFloatExpressionCode("result") }}
    }
{% elif operand=="%" %}
    /* TODO: Isn't this a very specific value only, of which we could
     * hardcode the constant result. Not sure how well the C compiler
     * optimizes UNARY_NEG_WOULD_OVERFLOW to this, but dividing by
     * -1 has to be rare anyway.
     */

    if (likely(b != -1 || !UNARY_NEG_WOULD_OVERFLOW(a))) {
        long result = a % b;

        // Sign handling.
        if (result != 0 && ((b ^ result) < 0) ) {
            result += b;
        }

        {{ target.getReturnFromLongExpressionCode("result") }}
    }
{% elif operand in "|^&" %}
    const long result = a {{operand}} b;
    {{ target.getReturnFromLongExpressionCode("result") }}
{% elif operand == "<<" %}
    if (unlikely(b < 0)) {
        SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ValueError, "negative shift count");
        return {{target.getExceptionResultIndicatorValue()}};
    }
    /* Short cut for zero shift or shifting zero. */
    if (a == 0 || b == 0) {
        {{ target.getReturnFromObjectExpressionCode("operand1", take_ref=True, check_exception=False) }}
    } else if (b >= LONG_BIT) {
        PyObject *operand1_long = PyLong_FromLong(a);
        PyObject *operand2_long = PyLong_FromLong(b);

        // TODO: Change this to using CLONG once we specialize that too.
        PyObject *result = _BINARY_OPERATION_LSHIFT_OBJECT_LONG_LONG(operand1_long, operand2_long);

        Py_DECREF(operand1_long);
        Py_DECREF(operand2_long);

        {{ target.getReturnFromObjectExpressionCode("result") }}
    } else {
        long c = a << b;

        if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
            PyObject *operand1_long = PyLong_FromLong(a);
            PyObject *operand2_long = PyLong_FromLong(b);

            // TODO: Change this to using CLONG once we specialize that too.
            PyObject *result = _BINARY_OPERATION_LSHIFT_OBJECT_LONG_LONG(operand1_long, operand2_long);

            Py_DECREF(operand1_long);
            Py_DECREF(operand2_long);

            {{ target.getReturnFromObjectExpressionCode("result") }}
        } else {
            {{ target.getReturnFromLongExpressionCode("c") }}
        }
    }
{% elif operand == ">>" %}
    if (unlikely(b < 0)) {
        SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ValueError, "negative shift count");
        return {{target.getExceptionResultIndicatorValue()}};
    }

    /* Short cut for zero shift or shifting zero. */
    if (a == 0 || b == 0) {
        {{ target.getReturnFromObjectExpressionCode("operand1", take_ref=True, check_exception=False) }}
    } else if (b >= LONG_BIT) {
        if (a < 0) {
            {{ target.getReturnFromIntConstantCode(-1) }}
        } else {
            {{ target.getReturnFromIntConstantCode(0) }}
        }
    } else {
        long r = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
        {{ target.getReturnFromLongExpressionCode("r") }}
    }


{% elif operand == "**" %}
    if (b < 0) {
        // TODO: Use CFLOAT once available.
        PyObject *operand1_float = PyFloat_FromDouble(a);
        PyObject *operand2_float = PyFloat_FromDouble(b);

        PyObject *result = _BINARY_OPERATION_POW_OBJECT_FLOAT_FLOAT(operand1_float, operand2_float);

        Py_DECREF(operand1_float);
        Py_DECREF(operand2_float);

        {{ target.getReturnFromObjectExpressionCode("result") }}
    } else {
        long temp = a;
        long ix = 1;
        long bb = b;

        while (bb > 0) {
            long prev = ix;
            if (bb & 1) {
                ix = (unsigned long)ix * temp;
                if (temp == 0) {
                    break;
                }
                if (ix / temp != prev) {
                    PyObject *operand1_long = PyLong_FromLong(a);
                    PyObject *operand2_long = PyLong_FromLong(b);

                    PyObject *result = _BINARY_OPERATION_POW_OBJECT_LONG_LONG(operand1_long, operand2_long);

                    Py_DECREF(operand1_long);
                    Py_DECREF(operand2_long);

                    {{ target.getReturnFromObjectExpressionCode("result") }}
                }
            }
            bb >>= 1;
            if (bb==0) {
                break;
            }
            prev = temp;
            temp = (unsigned long)temp * temp;

            if (prev != 0 && temp / prev != prev) {
                PyObject *operand1_long = PyLong_FromLong(a);
                PyObject *operand2_long = PyLong_FromLong(b);

                PyObject *result = _BINARY_OPERATION_POW_OBJECT_LONG_LONG(operand1_long, operand2_long);

                Py_DECREF(operand1_long);
                Py_DECREF(operand2_long);

                {{ target.getReturnFromObjectExpressionCode("result") }}
            }
        }

        {{ target.getReturnFromLongExpressionCode("ix") }}
    }
{% elif operand == "divmod" %}
    if (unlikely(b == 0)) {
        SET_CURRENT_EXCEPTION_TYPE0_STR(PyExc_ZeroDivisionError, "integer division or modulo by zero");
        return {{target.getExceptionResultIndicatorValue()}};
    }

    if (likely(b != -1 || !UNARY_NEG_WOULD_OVERFLOW(a))) {
        long a_div_b = a / b;
        long a_mod_b = (long)(a - (unsigned long)a_div_b * b);

        if (a_mod_b && (b ^ a_mod_b) < 0) {
            a_mod_b += b;
            a_div_b -= 1;
        }

        {{ target.getReturnTupleFromLongExpressionsCode("a_div_b", "a_mod_b") }}
    }
{% else %}
#error Operand {{operand}} not implemented in {{name}}
{% endif %}
    {
        PyObject *op1 = {{left.getAsObjectValueExpression("operand1")}};
        PyObject *op2 = {{right.getAsObjectValueExpression("operand2")}};

        // TODO: Could in-line and specialize these as well.
        PyObject *o = {{left.getSlotCallExpression(nb_slot, "PyLong_Type.tp_as_number->"+nb_slot, "op1", "op2")}};
        assert(o != Py_NotImplemented);

        {{left.releaseAsObjectValueStatement("op1")}}
        {{right.releaseAsObjectValueStatement("op2")}}

        {{ target.getReturnFromObjectExpressionCode("o") }}
    }
}
